import {Component, OnInit, ChangeDetectorRef } from '@angular/core';
import {Globals} from '../../globals';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ApiUrl} from '../../config/api-url';
import {BaseService} from '../../shared/service/base.service';
import {PageHelper} from '../../utils/page-helper-model';
import {ActivatedRoute, Router} from '@angular/router';
import {Consts} from '../../config/consts';
import {RoleIdEnum} from '../../enums/role-id.enum';
import {DeviceTypeEnum} from "../../enums/device-type.enum";

declare let $;

@Component({
  selector: 'app-device',
  templateUrl: './device.component.html',
  styleUrls: ['./device.component.less']
})
export class DeviceComponent implements OnInit {
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
    SUB_ACCOUNT: RoleIdEnum.SUB_ACCOUNT,
  };
  deviceTypeEnum = {
    VENDING_MACHINE:DeviceTypeEnum.VENDING_MACHINE,
    SCREEN_VENDING_MACHINE:DeviceTypeEnum.SCREEN_VENDING_MACHINE,
    OPEN_DOOR_VENDING_MACHINE:DeviceTypeEnum.OPEN_DOOR_VENDING_MACHINE,
    BLEND_VENDING_MACHINE:DeviceTypeEnum.BLEND_VENDING_MACHINE,
    ONE_TO_MANY_BOXES:DeviceTypeEnum.ONE_TO_MANY_BOXES,
  };
  burnTheNumberNzLoading = false;
  isMobile = Globals.isMobile();
  listOfData: any;
  // 分页
  pageHelper: PageHelper = new PageHelper;
  formModel: FormGroup;
  expandSet = new Set<number>();
  selectedValue: any;
  syntheticType:any;

  // 机构
  agencyList: [];
  // 运营商
  userList: [];
  // 门店
  merchantStoreList: [];
  // 设备类型
  deviceTypeList: [];
  //主板名称
  mainBoardList: [];

  // 显示二维码模态框
  qrCodeVisible = false;
  // 二维码内容
  qrCodeContent: any;
  // 下载二维码的文件名称
  fileName: any;

  // 显示批量生产设备码
  batchEstablishVisible = false;

  deviceStatistic: any;
  userInfo: any;

  // 显示设备设置
  deviceSettingVisible = false;
  device: any;

  // 显示设备类型设置
  deviceTypeVisible = false;

  // 显示设置设备脉冲
  deviceSetPulseVisible = false;

// 显示添加设备modal
  isVisible = false;

  systemConfig: any;

  // 显示远程烧号
  remoteWriteDeviceNoVisible = false;

  formModelDeviceNo: FormGroup;

  maintenanceAndReplaceShow = false;
  maintenanceAndReplace: any;

  // 发送测试
  deviceSendTestCmdVisible = false;


  // 批量修改设备状态
  batchOperationStatusVisible = false;
  deviceListByUpdateStatus = [];
  //批量修改设备 是否全选
  deviceAllSelected = false;
  //查看上线离线
  deviceOnlineOfflineVisible = false;
  //修改货道设备类型
  displayRackItemVisible = false;
  constructor(private fb: FormBuilder, public baseService: BaseService, private activatedRoute: ActivatedRoute, private router: Router, private cdr: ChangeDetectorRef) {
    this.buildForm();
    this.activatedRoute.queryParams.subscribe(params => {
      if (params['userId'] != null) {
        this.formModel.get('userId').setValue(params['userId']);
        this.listOfData = [];
        this.getDeviceData();
      } else if (params['deviceNo'] != null) {
        this.formModel.get('deviceNo').setValue(params['deviceNo']);
        this.listOfData = [];
        this.getDeviceData();
      } else {
        this.getDeviceData();
      }
    });
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.getAllUserOfName();
    this.getAllAgencyOfName();
    this.findAllMerchantStoreByUserInfo();
    this.findAllDeviceType();
    this.findDeviceStatistic();
    this.findSystemConfig();
  }

  buildForm() {
    this.formModel = this.fb.group({
      agencyId: ['', []],
      userId: ['', []],
      merchantStoreId: ['', []],
      deviceTypeId: ['', []],
      status: ['', []],
      networkIntensity: ['', []],
      deviceNo: ['', []],
      syntheticType: ['', []],
      productId: ['', []],
    });
  }
  onPageSizeChange(pageSize: any){
    // console.log(pageSize, 'pageSize');
    this.pageHelper.pageSize = pageSize;
    this.pageHelper.currentPage = 1;
    this.getDeviceData();
  }
  batchOperationStatus(){
    const list = [];
    if (this.pageHelper.totalItems==0){
        this.baseService.layer.messageError('暂无设备哦!');
        return;
    }
    if (this.baseService.zorro.setOfCheckedId.size == 0) {
        list.length = this.pageHelper.totalItems;
        // 先将集合清空
        this.baseService.zorro.listOfCurrentPageData = this.listOfData;
        // 调用全选方法
        this.baseService.zorro.onAllChecked(true);
        this.deviceAllSelected = true;
    }else{
      this.baseService.zorro.setOfCheckedId.forEach(item => {
          list.push(item);
      });
      this.deviceAllSelected = false;
    }
    this.deviceListByUpdateStatus = list;
    this.batchOperationStatusVisible = !this.batchOperationStatusVisible;
  }

  findDeviceStatistic() {
    // console.log(this.formModel.value)
    this.baseService.findListByMuchCondition(ApiUrl.DeviceUrl + '/findDeviceStatistic', this.formModel.value, this.pageHelper).subscribe(data => {
      if (data.status == 0) {
        this.deviceStatistic = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getDeviceData() {
    this.baseService.findListByMuchCondition(ApiUrl.DeviceUrl + '/list', this.formModel.value, this.pageHelper).subscribe(data => {
      if (data.status == 0) {
        this.listOfData = data.data.list;
        // console.log(123);
        // console.log(this.listOfData);
        this.pageHelper.totalItems = data.data.total;
        this.pageHelper.numPages = data.data.pages;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllAgencyOfName() {
    this.baseService.get(ApiUrl.AgencyUrl + '/getAllAgencyOfName').subscribe(data => {
      if (data.status == 0) {
        this.agencyList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  getAllUserOfName() {
    let agencyId = this.formModel.get('agencyId').value;
    if (agencyId == null) {
      agencyId = '0';
    }
    this.baseService.get(ApiUrl.UserUrl + '/getAllUserOfName?agencyId=' + agencyId).subscribe(data => {
      if (data.status == 0) {
        this.userList = data.data;
      } else {
        this.baseService.layer.messageError(data.msg);
      }
    });
  }

  findAllMerchantStoreByUserInfo() {
    let userId = this.formModel.get('userId').value;
    if (userId == null) {
      userId = '';
    }
    this.baseService.get(ApiUrl.MerchantStoreUrl + '/findAllMerchantStoreByUserInfo?userId=' + userId).subscribe(
      data => {
        if (data.status == 0) {
          this.merchantStoreList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  findAllDeviceType() {
    this.baseService.get(ApiUrl.DeviceTypeUrl + '/findAllDeviceType').subscribe(
      data => {
        if (data.status == 0) {
          this.deviceTypeList = data.data;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  nzPageIndexChange($event: number) {
    this.pageHelper.currentPage = $event;
    this.getDeviceData();
  }

  gainAgencyId($event: any) {
    this.getAllUserOfName();
  }

  gainUserId($event: any) {
    this.findAllMerchantStoreByUserInfo();
  }

  skipStore(data: any) {
    this.router.navigateByUrl('/store?userId=' + data.userId,
      {skipLocationChange: true});
  }

  // 确认按条件查找
  submitForm() {
    this.pageHelper.currentPage = 1;
    this.getDeviceData();
    this.findDeviceStatistic();
  }

  // 显示二维码
  showQrCode(deviceItem: any, deviceIds: any) {

    let isShowQRCode = false;
    if (deviceIds == null || deviceIds.length == 0){
      isShowQRCode = true;
      deviceIds = new Array();
      deviceIds.push(deviceItem.id)
    }
    let params = {
      deviceIds:deviceIds,
    }
    // console.log('params',params)
    this.baseService.post(ApiUrl.DeviceUrl + '/getDeviceQrCode', params).subscribe(
      data => {
        if (data.status == 0) {
          if (isShowQRCode){
            if (deviceItem.storeName != null) {
              this.fileName = deviceItem.storeName + '-' + deviceItem.deviceNo;
            } else {
              this.fileName = deviceItem.deviceNo;
            }
            this.qrCodeContent = data.data[0].fileName;
            this.qrCodeVisible = true;
          } else {
             this.createImg(data.data);
          }
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  // 从二维码子组件返回来
  setQrCodeVisible($event: any) {
    this.qrCodeVisible = $event;
  }

  // 批量下载
  batchDownload() {
    if (this.baseService.zorro.setOfCheckedId.size == 0) {
      this.baseService.layer.messageError('批量下载至少选中一个！');
      return;
    }

    let idList = new Array();
    this.baseService.zorro.setOfCheckedId.forEach(item => {
      idList.push(item);
    });
    this.showQrCode(null, idList);

  }


  // 选中全部
  checkedAll($event: boolean) {
    // 在这里获取当页的所有id

    // 先将集合清空
    this.baseService.zorro.listOfCurrentPageData = this.listOfData;

    // 调用全选方法
    this.baseService.zorro.onAllChecked($event);
  }

  // 选中单个
  checkedItem(id: any, $event: boolean) {
    // 先将集合清空
    this.baseService.zorro.listOfCurrentPageData = this.listOfData;
    this.baseService.zorro.onItemChecked(id, $event);
  }

  // 创建二维码
  img(str) {
    var out, i, len, c;
    out = '';
    len = str.length;
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        out += str.charAt(i);
      } else if (c > 0x07FF) {
        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      } else {
        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      }
    }
    return out;
  }

  createImg(idList) {
    const size = 384;
    const batchSize = 10; // 每次生成和下载的数量

    // 清空二维码容器
    $('#text').html('');

    let index = 0;
    let _this = this;
    // let list = [];
    function generateAndDownloadBatch() {
      for (let i = 0; i < batchSize && index < idList.length; i++) {
        const id = idList[index].id;
        const fileName = idList[index].fileName;
        const storeName = idList[index].storeName || '';
        const deviceNo = idList[index].deviceNo;
        // list.push(deviceNo);
        // 创建二维码
        const qrcode = $('#qrCode' + id).qrcode({
          render: 'canvas',
          text: fileName,
          width: size,
          height: size,
          background: '#ffffff',
          foreground: '#000000',
        });

        // 获取canvas元素和图像对象
        const canvas = qrcode.find('canvas').get(0);
        const img = new Image();
        img.src = canvas.toDataURL('image/png');

        img.onload = function() {
          canvas.width = size;
          canvas.height = size;
          const ctx = canvas.getContext('2d');

          // 清空画布
          ctx.clearRect(0, 0, canvas.width, canvas.height);

          // 绘制二维码
          ctx.drawImage(img, 0, 0);

          // 下载二维码
          const link = document.createElement('a');
          link.href = canvas.toDataURL('image/png');
          link.download = `${storeName}${deviceNo}.png`;

          const event = new MouseEvent('click');
          link.dispatchEvent(event);
        };

        index++;

        // console.log("index",index);
      }

      // 如果还有剩余的二维码未生成和下载，则延迟一段时间后继续生成和下载
      if (index < idList.length) {
        setTimeout(generateAndDownloadBatch, 2500); // 延迟200毫秒
        // console.log(list,'list')
      } else if (idList.length == index) {
        // 所有二维码生成和下载完成后取消选中的
        _this.baseService.zorro.onAllChecked(false);
      }
    }
    // 开始生成和下载
    generateAndDownloadBatch();
  }
  // 创建图片
  // createImg(idList) {
  //   // console.log(idList.length,'要生成二维码个数');
  //   // console.log(JSON.stringify(idList),'集合');
  //   // return
  //   var that = this;
  //   for (let i = 0; i < idList.length; i++) {
  //     var size = 384;
  //     $('#text').html('');
  //     let qrcodewidth = size;
  //     let qrcodeheight = size;
  //     let qrcode = $('#qrCode' + idList[i].id).qrcode({
  //       render: 'canvas',
  //       text: that.img(idList[i].fileName),
  //       width: qrcodewidth,
  //       height: qrcodeheight,
  //       background: '#ffffff',
  //       foreground: '#000000',
  //     });
  //     //canvas宽高
  //     let canvaswidth = qrcodewidth;
  //     let canvasheight = qrcodeheight;
  //     let canvas = qrcode.find('canvas').get(0);
  //     let img = new Image();
  //     img.src = canvas.toDataURL('image/png');
  //     img.onload = function() {
  //       canvas.width = canvaswidth;
  //       canvas.height = canvasheight;
  //       let ctx = canvas.getContext('2d');
  //       //设置画布背景
  //       ctx.fillStyle = '#ffffff';
  //       ctx.fillRect(0, 0, canvas.width, canvas.height);
  //
  //       //绘制二维码
  //       ctx.drawImage(img, 0, 0);
  //       let type = 'png';
  //       let idName = '#qrCode' + idList[i].id;
  //       let imgFile = $(idName + ' canvas').get(0).toDataURL();
  //       // 下载
  //       let link = document.createElement('a');
  //       // 设置下载内容（可以是网址）
  //       link.href = imgFile;
  //       // 设置文件名称
  //       link.download = idList[i].storeName != null ? idList[i].storeName : '';
  //       link.download = link.download + idList[i].deviceNo + '.' + type;
  //       let event = document.createEvent('MouseEvents');
  //       event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  //       link.dispatchEvent(event);
  //     };
  //   }
  //   // 取消选中的
  //   this.baseService.zorro.onAllChecked(false);
  // }


  // 解除绑定设备
  unBindingDevice(item: any) {
    this.baseService.layer.modalConfirm('确定要解绑[' + item.deviceNo + ']设备吗？', result => {
      if (result) {
        let body = {
          id: item.id,
          deviceNo: item.deviceNo,
          username: item.username,
          name: item.name
        };
        this.baseService.put(ApiUrl.DeviceUrl + '/unBindingDevice', body).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('解绑成功！');
              this.getDeviceData();
            } else {
              this.baseService.layer.messageError('解绑失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  // 批量创建设备
  batchEstablish() {
    this.batchEstablishVisible = true;
  }

  setBatchEstablishVisible($event: any) {
    this.batchEstablishVisible = $event;
    this.getDeviceData();
  }

  setSendTestCmdVisible($event: any) {
    this.deviceSendTestCmdVisible = $event;
  }

  // 分配设备给合作伙伴
  distributionDevice() {
    // if (this.baseService.zorro.setOfCheckedId.size == 0){
    //   this.baseService.layer.messageError('分配设备至少选中一个！');
    //   return;
    // }
    this.router.navigateByUrl('/device/device-distribution');
  }

  // 上下架
  updateStandUpAndDown(item) {
    var state = null;
    var msg = null;
    if (item.status == 1) {
      state = 0;
      msg = '确定要下架[' + item.deviceNo + ']设备吗？';
    } else {
      state = 1;
      msg = '确定要上架' + item.deviceNo + ']设备吗？';
    }

    this.baseService.layer.modalConfirm(msg, result => {
      if (result) {
        let body = {
          id: item.id,
          status: state,
        };
        this.baseService.put(ApiUrl.DeviceUrl + '/updateDeviceById', body).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('修改成功！');
              this.loadData();
            } else {
              this.baseService.layer.messageError('修改失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  // 确认按条件查找
  loadData() {
    this.pageHelper.currentPage = 1;
    this.getDeviceData();
  }

  unbindSum(data: any) {
    this.baseService.layer.modalConfirm('确定让设备能重新获得解绑的机会', result => {
      if (result) {
        let body = {
          id: data.id,
        };
        this.baseService.put(ApiUrl.DeviceUrl + '/updateUnbindSum', body).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('修改成功！');
              this.loadData();
            } else {
              this.baseService.layer.messageError('修改失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  clearFreightLane(deviceNo: string) {
    this.baseService.layer.modalConfirm('确定清除货道吗？', result => {
      if (result) {
        let body = {
          deviceNo: deviceNo,
        };
        this.baseService.post(ApiUrl.DeviceUrl + '/clearFreightLane', body).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('清除成功！');
              this.loadData();
            } else {
              this.baseService.layer.messageError('清除失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  // 发送测试协议
  sendTestCmd(data: any) {
    this.device = data;
    // console.log('this.device', this.device);
    this.deviceSendTestCmdVisible = true;
    // console.log('this.deviceSendTestCmdVisible', this.deviceSendTestCmdVisible);
  }

  /**
   * 查看上线离线时间点
   * */
  checkOnlineAndOffline(data:any){
    this.device = data;
    this.deviceOnlineOfflineVisible = true;
  }
  modifyTheTypeOfCargoLaneEquipmentShow(data){
    this.device = data;
    this.displayRackItemVisible = true;
  }
  restoreFactoryDefault(deviceId: number, status: number) {
    // console.log(status);
    if (status != 4) {
      this.baseService.layer.messageError('当前设备状态不支持恢复');
      return;
    }

    this.baseService.layer.modalConfirm('确定恢复出厂状态吗？', result => {
      if (result) {
        let body = {
          id: deviceId,
        };
        this.baseService.put(ApiUrl.DeviceUrl + '/restoreFactoryDefault', body).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('恢复成功！');
              this.loadData();
            } else {
              this.baseService.layer.messageError('恢复不成功：' + data.msg);
            }
          }
        );
      }
    });
  }

  findSystemConfig() {
    this.baseService.get(ApiUrl.SystemConfigUrl + '/findSystemConfig').subscribe(
      data => {
        if (data.status == 0) {
          this.systemConfig = data.data;
        } else {
          this.baseService.layer.messageError('查询失败：' + data.msg);
        }
      }
    );
  }

  editShow() {
    this.isVisible = true;
  }

  // 子组件向父组件传值
  setVisible(body) {
    this.isVisible = body.isVisible;
    this.getDeviceData();
  }

  hideMaintenanceAndReplace(isVisible) {
    // console.log(isVisible);
    this.maintenanceAndReplaceShow = isVisible;
  }

  // 维修替换
  updateMaintenanceAndReplace(isVisible) {
    this.maintenanceAndReplace = null;
    this.submitForm();
    this.hideMaintenanceAndReplace(isVisible);
    // console.log(item);
    // if (item.merchantStoreId > 0){
    //   this.baseService.layer.messageError('设置维修前请将设备解绑');
    //   return;
    // }
    // this.baseService.layer.modalConfirm('确定将[' + item.deviceNo + ']设备维修替换吗？', result => {
    //   if (result) {
    //     let body = {
    //       id: item.id,
    //       status: 5,
    //     };
    //     this.baseService.put(ApiUrl.DeviceUrl + '/updateDeviceById', body).subscribe(
    //       data => {
    //         if (data.status == 0) {
    //           this.baseService.layer.messageSuccess('修改成功！');
    //           this.submitForm();
    //           this.hideMaintenanceAndReplace(false);
    //         } else {
    //           this.baseService.layer.messageError('修改失败：' + data.msg);
    //         }
    //       }
    //     );
    //   }
    // });

  }

  deviceBuy() {
    this.router.navigateByUrl('/product/buy-device');
  }

  setRemoteWriteDeviceNoVisible(isVisible){
    this.remoteWriteDeviceNoVisible = isVisible;
  }

  setBatchOperationStatusVisible(isVisible){
    this.baseService.zorro.setOfCheckedId.forEach(item=> {
      this.baseService.zorro.onItemChecked(item, false);
    });
    this.deviceListByUpdateStatus = [];
    this.batchOperationStatusVisible = isVisible;
  }

  setDeviceTypeVisible($event: boolean, item: any) {
    if ($event != null) {
      this.deviceTypeVisible = $event;
      this.device = item;
    } else {
      this.deviceTypeVisible = $event;
      this.submitForm();
    }
  }
  deviceOnlineOfflineEmitVisible($event: boolean){
    this.deviceOnlineOfflineVisible = $event;
  }
  modifyTheTypeOfCargoLaneEquipmentEmitVisible($event: boolean){
    this.displayRackItemVisible = $event;
  }

  getConfiguration(item: any) {
    this.baseService.post(ApiUrl.DeviceUrl + '/getConfiguration', item).subscribe(
      data => {
        if (data.status == 0) {
          this.baseService.layer.messageSuccess('发送成功！');
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }
}
